<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="我的证件"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 50px);" :show-scrollbar="false">
			<free-divider></free-divider>

			<view class="pl-2 pr-2 py-3">
				<view class="dfex border-bottom mt-2 pb-3" v-for="(item,index) in newList" :key="index">
					<view class="font-14">{{item.papersName}}</view>
					<img class="pl-5" style="width: 144px; height: 88px;" @error="handleImageError"
						:src="getFullImageUrl(item.papersPhotoUrl)" @click="previewImage(item, index)" />
					<view class="dfex text-8ED0F2 pl-2 mt-14 font-14" style="width: 100px;">
						<view v-if="userInfo.parentId == null" @click="previewImage(index)">下载</view>
						<view v-else>下载</view>

						<view v-if="userInfo.parentId == null" @click="headDelete(item.id)">删除</view>
						<view v-else>删除</view>
					</view>
				</view>
				<view class="text-center text-999999 font-14" v-if="newList.length === 0">
					<view class="iconfont text-999999 icon-zanwushuju font-48 pb-1"></view>
					<view class="text-999999 font-15">暂无数据</view>
				</view>
			</view>

			<ferrButton v-if="userInfo.parentId === null" title="添加新证件" @click="showAddBox"></ferrButton>
			<ferrButton v-else title="添加新证件"></ferrButton>
			<!-- 修改名字|修改微信号 弹框-->
			<free-confirm ref="confirm" :title="confirmTitle">
				<u-field v-model="currentPapersName" label="证件名称" placeholder="请输入名称">
				</u-field>
				<view class="flex-y py-3 pl-2 pr-2">
					<view class="">
						证件上传
					</view>
					<u-upload ref="uUpload" :form-data="{'biz':'temp'}" :max-size="4 * 1024 * 1024" :header="header"
						@on-success="uploadSuccess" :action="getUploadUrl()" max-count="1"></u-upload>
				</view>
				<view class="font-12 text-999999 pl-1">图片限制不能超过4MB</view>
			</free-confirm>
		</scroll-view>

		<view class="page-code" v-if="currentIndex !== null">
			{{ currentIndex + 1 }} / {{ images.length }}
		</view>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import $U from "@/common/free-lib/util.js";
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	import freeAvater from "@/components/free-ui/free-avater.vue";
	import freeDivider from "@/components/free-ui/free-divider.vue";
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import freeConfirm from "@/components/free-ui/free-confirm.vue";
	export default {
		components: {
			freeAvater,
			freeDivider,
			freeConfirm,
			ferrButton
		},
		data() {
			return {

				confirmType: "",
				confirmText: '',
				papersPhotoUrl: '',
				newList: [],
				header: $H.getTokenHeader(),
				currentPapersName: '',
				userInfo: null,
				images: [],
				currentIndex: null // 当前图片的索引
			}
		},
		computed: {
			confirmTitle() {
				return this.confirmType == 'username' ? '添加新证件' : '添加新证件'
			},
			isClickable() {
				return this.userInfo && this.userInfo.parentId === null;
			}
		},
		onLoad() {
			const userInfo = uni.getStorageSync('userInfo');
			this.userInfo = userInfo
			this.NewList()
		},
		methods: {
			handleImageError() {
				uni.showToast({
					title: '图片格式不支持jpeg，请重新上传',
					icon: 'none',
					duration: 4000
				});

			},

			download(url) {
				$H.downloadPic(url);
			},
			// getFullPicUrl(url) {
			// 	return $H.getFullImageUrl(url);
			// },
			// 拼接图片方法
			getFullImageUrl(imagePath, index) {
				return getImageUrl(imagePath);
			},
			previewImage(item) {
				const imageUrls = this.newList.map(img => this.getFullImageUrl(img.papersPhotoUrl)); // 所有图片的 URL 数组
				const currentUrl = this.getFullImageUrl(item.papersPhotoUrl); // 当前点击的图片 URL
				const currentIndex = imageUrls.indexOf(currentUrl); // 获取当前图片在数组中的索引

				uni.previewImage({
					urls: imageUrls,
					current: currentUrl,
					indicator:"number",
					loop:true,
					success: () => {
						uni.showToast({
							title: '长按图片可保存',
							icon: 'none',
							duration: 5000 // 5秒钟的显示时间
						});
					}
				});
			},


			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			uploadSuccess(response) {
				if (response.code === 0) {
					uni.showToast({
						title: '图片上传成功',
						icon: 'none'
					});

					// Check if basePhoto already contains an image, replace it with the new one
					if (this.form.basePhoto.length > 0) {
						this.form.basePhoto[0] = {
							url: response.data,
							message: response.message
						};
					} else {
						// If basePhoto is empty, add the new image
						this.form.basePhoto.push({
							url: response.data,
							message: response.message
						});
					}
				} else {
					uni.showToast({
						title: response.message || '图片上传失败',
						icon: 'none'
					});
				}
			},
			NewList() {
				$H.post('/basisInform/papersManage/agriculture/List', {}, {}).then(res => {
					this.newList = res.result || []
				}).catch(error => {
					uni.showToast({
						title: "网络错误，请稍后再试",
						icon: 'none'
					});
				});
			},
			headDelete(id) {
				uni.showModal({
					title: '提示',
					content: '确定删除该证件吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中'
							});
							$H.post(`/basisInform/papersManage/agriculture/delete?id=${id}`).then(res => {
								uni.hideLoading();
								if (res.success) {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});
									this.NewList();
								} else {
									uni.showToast({
										title: res.message || '删除失败',
										icon: 'none'
									});
								}
							}).catch(err => {
								uni.hideLoading();
								uni.showToast({
									title: err.message,
									icon: 'none'
								});
							});
						}
					}
				});
			},


			showAddBox() {
				const userId = $U.getStorage("id");

				this.$refs.confirm.show((close) => {
					let files = [];
					// 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
					files = this.$refs.uUpload.lists.filter(val => {
						return val.progress == 100;
					})
					if (files.length == 0) {
						uni.showToast({
							title: '请上传文件',
							icon: 'none'
						});
						return;
					}
					if (!this.currentPapersName) {
						uni.showToast({
							title: '请输入证件名称',
							icon: 'none'
						});
						return;
					}
					$H.post('/basisInform/papersManage/upper/add', {
						papersManageItemList: [{
							papersName: this.currentPapersName,
							papersPhotoUrl: files[0].response.message
						}, ],
						userId: userId

					}, {}).then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							})
							this.currentPapersName = '';
							this.NewList();
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							})
						}

						close();
					}).catch(err => {
						uni.showToast({
							title: err.message,
							icon: 'none'
						});
					});
					close();
				});

			}

		}
	}
</script>

<style>
	.page-code {
		position: absolute;
		bottom: 10px;
		right: 10px;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		padding: 5px;
		border-radius: 5px;
	}
</style>